const http = require('http');

// 使用内置http模块的DeepSeek API测试脚本
function httpRequest(options, postData = null) {
  return new Promise((resolve, reject) => {
    const req = http.request(options, (res) => {
      let data = '';
      
      res.on('data', (chunk) => {
        data += chunk;
      });
      
      res.on('end', () => {
        resolve({
          statusCode: res.statusCode,
          headers: res.headers,
          data: JSON.parse(data || '{}')
        });
      });
    });
    
    req.on('error', (error) => {
      reject(error);
    });
    
    if (postData) {
      req.write(postData);
    }
    
    req.end();
  });
}

// 测试DeepSeek API连接
async function testDeepSeekAPI() {
  try {
    console.log('开始测试DeepSeek API连接...');
    
    // 1. 测试健康检查端点
    console.log('1. 测试健康检查端点...');
    const healthOptions = {
      hostname: 'localhost',
      port: 5000,
      path: '/api/health',
      method: 'GET'
    };
    
    const healthResponse = await httpRequest(healthOptions);
    console.log('   ✓ 健康检查通过:', healthResponse.data);
    
    // 2. 测试内容生成端点
    console.log('2. 测试内容生成端点...');
    const generateOptions = {
      hostname: 'localhost',
      port: 5000,
      path: '/api/generate',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      }
    };
    
    const postData = JSON.stringify({
      topic: '人工智能',
      type: 'article'
    });
    
    const generateResponse = await httpRequest(generateOptions, postData);
    
    console.log('   ✓ 内容生成请求已发送，状态码:', generateResponse.statusCode);
    console.log('   ✓ 响应内容摘要:', {
      title: generateResponse.data.title,
      source: generateResponse.data.source,
      success: generateResponse.data.success,
      hasError: !!generateResponse.data.error,
      hasDetails: !!generateResponse.data.details,
      hasDebug: !!generateResponse.data.debug
    });
    
    // 输出错误处理信息（如果有）
    if (generateResponse.data.error) {
      console.log('   注意：响应包含错误信息:', generateResponse.data.error);
    }
    
    if (generateResponse.data.details) {
      console.log('   详细错误信息:', generateResponse.data.details);
    }
    
    // 检查是否使用了模拟内容
    if (generateResponse.data.source === 'mock') {
      console.log('   系统使用了模拟内容，说明DeepSeek API调用失败');
      
      // 查看服务器日志以获取更详细的错误信息
      console.log('\n请查看服务器日志以获取更详细的DeepSeek API错误信息');
      console.log('可能的错误原因：');
      console.log('1. DeepSeek API余额不足');
      console.log('2. API Key无效');
      console.log('3. 网络连接问题');
      console.log('4. API端点配置错误');
    }
    
    console.log('\n测试完成！');
    return {
      success: generateResponse.statusCode === 200,
      statusCode: generateResponse.statusCode,
      message: 'DeepSeek API测试完成'
    };
    
  } catch (error) {
    console.error('测试失败:', error.message);
    return {
      success: false,
      message: error.message
    };
  }
}

// 运行测试
if (require.main === module) {
  testDeepSeekAPI().then(result => {
    console.log('\n最终测试结果:', result);
  });
}

module.exports = testDeepSeekAPI;